var Bulletins = mongoose.model('community_bulletins');
var Community = mongoose.model('community');
var Supplement = mongoose.model('community_supplements');
var Users = mongoose.model('user');
var async = require('async');
var toolUtil = require('../common/utils/toolUtil');
var geolib = require('geolib');
var cacheUtil = require('../common/utils/cacheUtil');
var moment = require('moment');
var communitySupplement = mongoose.model('community_supplements');
var UserFollowups = mongoose.model('user_followups');
var freshNews = mongoose.model('system_freshNews');
var communityApplication = mongoose.model('community_applications');
var systemService = require('./systemService');
var Banner = mongoose.model('community_banner');
var BannerBind = mongoose.model('community_banner_bind');
var communityGroup = mongoose.model('community_group');
var mysqlUtil = require('../common/utils/mysqlUtil');

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  start   */
var SystemAppstartinfos = mongoose.model('system_appStartInfo');
var Question = mongoose.model('question');
var Goods = mongoose.model('goods');
var UserInvitationShare = mongoose.model('user_invitation_share');
var UserInvitation = mongoose.model('user_invitation');
var ModeratorManager = mongoose.model('moderatorManager');
var ModeratorManagerOperationNote = mongoose.model('moderatorManagerOperationNote');
var ExcelJS = require('exceljs');
var fs = require('fs');
var Workbook = ExcelJS.Workbook;
var Region = mongoose.model('masterData_Regions');
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */

/**
 * 根据小区ObjID查询所有公告
 */
exports.getCommunityBulletinService = function (page, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;
            Bulletins.find({
                'community': user.community._id,
                isValid: true
            }, '_id title imageURL dateCreated').sort('-dateCreated').skip(index).limit(listPageSize).exec(callback);
        }
    });
};

exports.getDetailCommunityBulletinService = function (bulletinId, callback) {
    Bulletins.findOne({_id: bulletinId}, '_id title imageURL desc dateCreated', function (err, result) {
        if (result != null) {
            var date = moment(result.dateCreated).format('YYYY-MM-DD HH:mm');
            var header = '<B><font  size="5">' + result.title + '</font></B><br>' + date + '<br><br>'
            result.desc = header + result.desc;
        }
        callback(err, result);
    });
};

exports.postCommunityApplicationService = function (input, callback) {
    var temp = new communityApplication(input);
    temp.save(callback);
};


/**
 * 发布公告
 */
exports.postCommunityBulletinService = function (token, input, callback) {

    if (input.id == null) {
        var temp = new Bulletins();
        temp.title = input.title;
        temp.desc = input.desc;
        temp.imageURL = input.imageURL;
        temp.community = input.community;
        temp.save(function (err, notice) {
            callback(err, null);
            systemService.generateTopicHtml(temp, noticePath);
        });
    } else {
        Bulletins.update({_id: input.id}, {
            title: input.title,
            desc: input.desc,
            imageURL: input.imageURL,
            community: input.community
        }, callback);
        systemService.generateTopicHtml(input, noticePath);
    }
};

/**
 * 发布公告
 */
exports.postCommunityBulletinServiceByModerator = function (token, input, callback) {

    var temp = new Bulletins();
    temp.title = input.title;
    temp.desc = input.desc;
    temp.imageURL = input.imageURL;
    temp.community = input.community;
    temp.isValid = true;
    temp.save(function (err, notice) {
        callback(err, null);
        systemService.generateTopicHtml(temp, noticePath);
    });

    var banner = new Banner(input);
    banner.contentId = temp._id;
    banner.openType = 2;
    banner.contentUrl = NoticeHost + '/' + temp._id + '.html';
    banner.imageURL = input.imageUrl;
    banner.tag = freshName.notice.tagName;
    banner.bgColor = freshName.notice.bgColor;
    banner.message = input.title;
    banner.isValid = true;
    banner.save();

    var temp2 = new BannerBind();
    temp2.bannerId = banner._id;
    temp2.community = input.community;
    temp2.type = 2;
    temp2.displayOrder = moment().format('YYYYMMDDHHmmss');
    temp2.save();

    input.tag = freshName.notice.tagName;
    input.bgColor = freshName.notice.bgColor;

    var temp1 = new freshNews();

    temp1.openType = 1;
    temp1.tag = input.tag;
    temp1.newsId = temp._id;
    //temp1.createdBy = input.contentCreatedBy;
    temp1.title = input.title;
    temp1.bgColor = input.bgColor;
    temp1.community = input.community;
    temp1.displayOrder = moment().format('YYYYMMDDHHmmss');
    temp1.url = NoticeHost + '/' + temp._id + '.html';
    temp1.save();
};

//获取小区详细信息
exports.getCommunityByCommunityIdService = function (token, communityId, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            Community.findById(communityId, '_id communityName households country province city county populationSize communityAddress communityLogo communityPostCode location phoneList')
                .populate('country', '_id name').populate('province', '_id name').populate('county', '_id name')
                .exec(function (err, result) {
                    if (err) {
                        callback(err, null);
                    } else {
                        if (result == null) {
                            var msg = {
                                "message": 'No such community'
                            };
                            callback(msg, null);
                        } else {
                            Users.count({'community': communityId}, function (err, count) {
                                if (result._doc != null) {
                                    result._doc['numberOfUser'] = count;
                                }
                                Users.count({'community': communityId, 'userType': 'talent'}, function (err, count) {
                                    result._doc['numberOfTalent'] = count;
                                    if (user.authenticationStatus && user.huanxinUserName != '66customerservice') {
                                        if (user.mobilePhone != null && user.mobilePhone.indexOf('400400') == 0) {
                                            result._doc['switchFlag'] = true;
                                        } else {
                                            result._doc['switchFlag'] = false;
                                        }
                                    } else {
                                        result._doc['switchFlag'] = true;
                                    }
                                    callback(err, result);
                                })
                            })
                        }
                    }
                });
        }
    });
};

exports.backOfficeGetCommunityDetailService = function (communityId, callback) {
    Community.findOne({_id: communityId}, function (err, result) {
        if (result.communityLogo != null) {
            result._doc.communityLogo = fastDfsHostIp + result.communityLogo
        }
        callback(err, result);
    });
};

//根据小区名字进行模糊查询
exports.searchByCityAndNameService = function (cityId, communityName, callback) {
    Community.find({
        'city': cityId,
        'communityName': new RegExp(communityName)
    }, '_id communityName country province city county populationSize communityAddress communityPostCode x_position y_position')
        .populate('country', '_id name').populate('province', '_id name').populate('city', '_id name').populate('county', '_id name').exec(callback);
};

// //======================Communities related=================================


exports.getCommunityListByCoordinates = function (latitude, longitude, callback) {

    //restClient.get('http://api.map.baidu.com/place/v2/search?&query=小区&region=上海&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0&location='
    //+ latitude + ',' + longitude, function (data, response) {
    //    if (response.statusCode == 200) {
    //
    //        Community.findOne({'communityName': '宝宝树66小区'}, function (err, result) {
    //            var temp = {
    //                "name": result.communityName,
    //                "location": {
    //                    "lat": result.location.latitude,
    //                    "lng": result.location.longitude
    //                },
    //                "address": result.communityAddress,
    //                "detail_info": {
    //                    "distance": 0
    //                }
    //            };
    //            var communities = JSON.parse(data);
    //            communities.results.unshift(temp);
    //            callback(null, communities);
    //        });
    //
    //
    //    } else {
    //        var err = {
    //            "message": 'statusCode:' + response.statusCode
    //        };
    //        callback(err, null);
    //    }
    //
    //}).on('error', function (err) {
    //    logger.error('get Community List by Coordinates went wrong on the request' + err.message);
    //});

    Community.find({isValid: true}, '', function (err, results) {
        var communities = {
            "results": []
        };
        results.forEach(function (result) {

            var dis = '';

            if (latitude == 0 || longitude == 0) {
                dis = ''
            } else {
                var distance = geolib.getDistance(
                    {latitude: latitude, longitude: longitude},
                    {latitude: result.location.latitude, longitude: result.location.longitude}
                );
                if (distance > 1000) {
                    var aa = distance / 1000;
                    dis = aa.toFixed(1) + 'km';
                } else {
                    dis = distance + 'm';
                }
            }

            var temp = {
                "_id": result._id,
                "name": result.city + '  ' + result.communityName,
                "location": {
                    "lat": result.location.latitude,
                    "lng": result.location.longitude
                },
                "address": result.communityAddress,
                "detail_info": {
                    "distance": dis
                },
                "order": distance
            };
            communities.results.unshift(temp);
        });

        communities.results.sort(function (a, b) {
            return a.order - b.order;
        });
        communities.results.forEach(function (t) {
            t.order = undefined;
        });

        callback(null, communities);
    });

};

/**
 * 获取小区达人排行榜
 * @param token
 * @param callback
 */
exports.getCommunityTalentService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Users.find({
                'userType': 'talent',
                'community': user.community._id
            }, '_id nickName images userPortrait speciality gender authenticationStatus').populate('userPortrait', '_id value')
                .exec(function (err, results) {
                    if (results != null) {
                        async.each(results, function (talent, callbackInner) {
                            UserFollowups.findOne({
                                'user': user._id,
                                'followUser': talent._id
                            }, '', function (err, result) {
                                if (result == null) {
                                    talent._doc['isFollowup'] = 'No'
                                } else {
                                    talent._doc['isFollowup'] = 'Yes'
                                }
                                callbackInner();
                            })
                        }, function (err) {
                            callback(err, results);
                        })

                    }
                })
        }
    });
}

exports.getCommunityTalentNewService = function (page, token, callback) {

    var index = Number(page) * listPageSize;

    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Users.find({
                'userType': 'talent',
                'community': user.community._id
            }, '_id nickName images userPortrait speciality gender authenticationStatus').populate('userPortrait', '_id value').skip(index).limit(listPageSize)
                .exec(function (err, results) {
                    if (results != null) {
                        async.each(results, function (talent, callbackInner) {
                            UserFollowups.findOne({
                                'user': user._id,
                                'followUser': talent._id
                            }, '', function (err, result) {
                                if (result == null) {
                                    talent._doc['isFollowup'] = 'No'
                                } else {
                                    talent._doc['isFollowup'] = 'Yes'
                                }
                                callbackInner();
                            })
                        }, function (err) {
                            callback(err, results);
                        })
                    }
                })
        }
    });
}


/**
 * 根据关键字查询
 * @param keyword
 * @param callback
 */
exports.getCommunityListByKeywordService = function (keyword, latitude, longitude, callback) {

    Community.find({'communityName': new RegExp(keyword)}, '', function (err, results) {
        var communities = {
            "results": []
        };
        results.forEach(function (result) {
            var distance = geolib.getDistance(
                {latitude: latitude, longitude: longitude},
                {latitude: result.location.latitude, longitude: result.location.longitude}
            );
            if (distance > 1000) {
                distance = distance / 1000;
                distance = distance.toFixed(1) + 'km';
            } else {
                distance = distance + 'm';
            }
            var temp = {
                "name": result.communityName,
                "location": {
                    "lat": result.location.latitude,
                    "lng": result.location.longitude
                },
                "address": result.communityAddress,
                "detail_info": {
                    "distance": distance
                }
            };
            communities.results.unshift(temp);
        });

        callback(null, communities);
    });

    //restClient.get('http://api.map.baidu.com/place/v2/search?&query=小区、' + keyword + '&region=上海&scope=2&output=json&ak=AvRqTglpaKICTZ5iwyn06KZj&radius=1000&page_size=20&page_num=0&location='
    //+ latitude + ',' + longitude, function (data, response) {
    //    if (response.statusCode == 200) {
    //        callback(null, JSON.parse(data));
    //    } else {
    //        var err = {
    //            "message": 'statusCode:' + response.statusCode
    //        };
    //        callback(err, null);
    //    }
    //}).on('error', function (err) {
    //    logger.error('get Community List by keyword went wrong on the request' + err.message);
    //});
};

/**
 * 获取商户列表
 */
exports.getCommunityAroundListService = function (page, status, token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var index = Number(page) * listPageSize;
            if (status == '全部') {
                CommunityAround.find({'community': user.community._id}, 'category status name images address title desc telephone businessHours averageConsumption').skip(index).limit(listPageSize).populate('category', '_id value').exec(callback);
            } else {
                CommunityAround.find({
                    'status': status,
                    'community': user.community._id
                }, 'category status name images address title desc telephone businessHours averageConsumption').skip(index).limit(listPageSize).populate('category', '_id value').exec(callback);
            }
        }
    })
};

/**
 * 获取商户详情
 */
exports.getCommunityAroundDetailsService = function (id, callback) {
    CommunityAround.findOne({_id: id}, 'category status name images address title album desc telephone businessHours averageConsumption comments.desc comments.createdBy comments.dateCreated dateCreated createdBy').populate('category', '_id value')
        .populate('comments.createdBy', '_id nickName images').populate('createdBy', '_id nickName').exec(function (err, results) {
            if (results != null && results.comments != null) {
                results.comments.sort(function (c1, c2) {
                    return c2.dateCreated - c1.dateCreated;
                });
            }
            callback(null, results);
        });
};

/**
 * 小区周边评论
 */
exports.postCommentService = function (aroundId, token, input, callback) {
    async.waterfall([
        function (callbackInner) {
            CommunityAround.findOne({'_id': aroundId}, function (err, result) {
                callbackInner(null, result);
            })
        },
        function (result, callbackInner) {
            if (result == undefined) {
                var err = {
                    "message": 'CommunityAround not found'
                };
                callback(err, null);
            } else {

                toolUtil.getUserByToken(token, function (err, user) {
                    if (err) {
                        callback(err, null);
                    } else {
                        var commend = {
                            'desc': input.desc,
                            'createdBy': user._id
                        };
                        CommunityAround.update({_id: aroundId}, {$push: {'comments': commend}}).exec(callback);
                    }
                });
            }
        }
    ])
}

/**
 * 查询全部小区
 */
exports.getAllCommunityService = function (callback) {

    Community.find(null).populate('groups', 'groupName').exec(function (err, results) {
        if (results != null) {
            callback(null, results);
        } else {
            var msg = {
                "message": 'No such community'
            }
            callback(msg, null);
        }
    });
};

exports.getAllCommunityFromSQLService = function (callback) {

    var sql = 'select _id objId, communityName, isValid, communityAddress, city, groups, convert(dateEffective, char) dateEffective from 66xiaoqu_rec.community where dateEffective is not null'
    mysqlUtil.queryBI(sql, function (err, result) {
        callback(err, result)
    })

};

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170912  start   */
// 下载小区大使信息Excel
exports.downLoadModeratorManagerInfoData = function (req, res, callback) {
    var ymdhmss = moment(Date.now()).format('YYYYMMDDHHmmssSSS');
    var name = 'ModeratorManager_' + ymdhmss + '.xlsx';
    // var filePath = outPutModeratorManagerInfoBasePath.replace(/xlsx/, "txt"); // txt文件
    var filePath = outPutModeratorManagerInfoBasePath; // excel文件
    res.download(filePath, name);
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170912  end   */

/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170925  start   */
// 生成小区大使信息txt文件
exports.exportModeratorManagerInfoData = function (req, res, callback) {
    console.log("exportModeratorManagerInfoData real start...");

    try{
        var limitCount = 100; // mongodb每次查询件数
        var parallelLimitCount = 4; // 限制N个并行
        var exeCount = 0;
        var eachSeriesInnerCount = 0;

        var option = {"userRole" : 4}; // 小区大使
        // var option = {}; // 全部用户

        var wb = new Workbook();
        var ws = wb.addWorksheet('ModeratorManager');

        // 自动覆盖旧版本，只能同时出现一个
        // var fileName = outPutModeratorManagerInfoBasePath.replace(/xlsx/, "txt"); // txt文件
        var fileName = outPutModeratorManagerInfoBasePath; // excel文件

        var dataArray = [];
        async.waterfall([
            function(callbackInnerTempTemp) {
                // 先删除已存在文件
                logger.info('导出文件路径: ' + fileName);
                if(fs.existsSync(fileName)) {
                    logger.info('删除旧文件.');
                    fs.unlinkSync(fileName);
                    callbackInnerTempTemp(null, null);
                } else {
                    logger.info('不存在旧文件.');
                    callbackInnerTempTemp(null, null);
                }
            },
            function(param1, callbackInnerTempTemp) {

                Users.count(option, function (err, tempUserCount) {
                    logger.info('小区大使件数:' + tempUserCount);
                    if(tempUserCount > 0) {
                        logger.info('分页，每次取得件数:' + limitCount);
                        var tmpCountCount = 0;
                        var startDateSelect = req.body.startDateSelect;
                        var endDateSelect = req.body.endDateSelect;

                        /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 start */
                        // var dateArr = toolUtil.getArrayDateByStartEndDate(startDateSelect, endDateSelect);
                        var dateArr = toolUtil.getArrayDateByStartEndDateMin(startDateSelect, endDateSelect);
                        var length = dateArr.length;
                        logger.info('查询天数:' + length);
                        /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 end */

                        var startDate = moment(startDateSelect, "YYYY-MM-DD").format();
                        var endDate = moment(endDateSelect, "YYYY-MM-DD").add(1, "days").format();
                        // var testDate = moment(startDate).add(-6, "hour").format();

                        var dateOption = {'dateCreated': {$gte: startDate, $lt: endDate}};

                        var endCount = parseInt((tempUserCount - 1) / limitCount) + 1;
                        var countArray = [];
                        for(var i = 0; i < tempUserCount; i = i + limitCount) {
                            countArray.push(i);
                        }
                        logger.info(countArray);
                        logger.info('预计分页执行次数:' + endCount);
                        async.eachSeries(countArray, function (skipCount, callbackSkipCountInner) {
                        // for(var i = 0; i < tempUserCount; i = i + limitCount) {
                            logger.debug('for循环...' + skipCount);
                            Users.find(option, "_id mobilePhone nickName community cityId")
                                // .populate('community', 'communityName')
                                // .populate('cityId', 'name')
                                .limit(limitCount)
                                // .skip(i)
                                .skip(skipCount)
                                .sort({"_id": 1})
                                .exec(function (err2, usersData) {
                                    logger.debug('Users.find...' + skipCount);
                                    if (usersData != null) {

                                        async.eachSeries(usersData, function (tempUser, callbackEachSeriesInner) {
                                        logger.debug('async.eachSeriesN个执行完成...' + ++eachSeriesInnerCount);
                                        // usersData.forEach(function (tempUser, index, array) {
                                            var userId = tempUser._id.toString();
                                            // 并行-修改为串行
                                            async.parallelLimit([
                                            // async.series([
                                                /* 选定日期范围内是否每天登录 change wangc 20170921 start */
                                                function (callbackInner) {
                                                    // 选定日期范围内是否每天都登录过至少一次
                                                    var tempLoginDatesArr = [];
                                                    logger.debug('每天登录start...' + eachSeriesInnerCount);
                                                    // async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
                                                    //     var startTemp = tempDate;
                                                    //     var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
                                                    //     SystemAppstartinfos.findOne({
                                                    //         "userId": userId,
                                                    //         "dateCreated": {$gte: startTemp, $lt: endTemp}
                                                    //     }, function (tempErr, tempEssence) {
                                                    //         tempLoginDatesArr.push(!tempEssence ? 1 : 0);
                                                    //         callbackTempInner(false);
                                                    //     });
                                                    // }, function (tempErr) {
                                                    //     logger.debug('每天登录end...' + eachSeriesInnerCount);
                                                    //     callbackInner(null, tempLoginDatesArr);
                                                    // });

                                                    callbackInner(null, 0);
                                                },
                                                /* 选定日期范围内是否每天登录 change wangc 20170921 end */
                                                function (callbackInner) {
                                                    // [邀请分享]表取得小区大使对应的邀请码,再到[用户]表中取得邀请码一致的人的件数
                                                    // 选定日期范围内邀请成功总数
                                                    logger.debug('邀请成功总数start...' + eachSeriesInnerCount);
                                                    UserInvitation.count({
                                                        "inviter": userId,
                                                        'dateCreated': {$gte: startDate, $lt: endDate}
                                                    }, function (err, successInviteUserCount) {
                                                        logger.debug('邀请成功总数end...' + eachSeriesInnerCount);
                                                        callbackInner(null, successInviteUserCount);
                                                    });
                                                },
                                                function (callbackInner) {
                                                    // 问问:question
                                                    // 追加开始结束日期
                                                    // 'dateCreated': {$gte: startDate, $lt: endDate}
                                                    logger.debug('问问start...' + eachSeriesInnerCount);
                                                    Question.count({
                                                        "createdBy": userId,
                                                        "category": "question",
                                                        'dateCreated': {$gte: startDate, $lt: endDate}
                                                    }, function (err, questionCount) {
                                                        logger.debug('问问end...' + eachSeriesInnerCount);
                                                        callbackInner(null, questionCount);
                                                    });
                                                },
                                                function (callbackInner) {
                                                    // 说说:share
                                                    // 追加开始结束日期
                                                    // 'dateCreated': {$gte: startDate, $lt: endDate}
                                                    logger.debug('说说start...' + eachSeriesInnerCount);
                                                    Question.count({
                                                        "createdBy": userId,
                                                        "category": "share",
                                                        'dateCreated': {$gte: startDate, $lt: endDate}
                                                    }, function (err, shareCount) {
                                                        logger.debug('说说end...' + eachSeriesInnerCount);
                                                        callbackInner(null, shareCount);
                                                    });
                                                },
                                                function (callbackInner) {
                                                    // 闲置
                                                    // 追加开始结束日期
                                                    // 'dateCreated': {$gte: startDate, $lt: endDate}
                                                    logger.debug('闲置start...' + eachSeriesInnerCount);
                                                    Goods.count({
                                                        "createdBy": userId,
                                                        'dateCreated': {$gte: startDate, $lt: endDate}
                                                    }, function (err, goodsCount) {
                                                        logger.debug('闲置end...' + eachSeriesInnerCount);
                                                        callbackInner(null, goodsCount);
                                                    });
                                                },
                                                // 置顶
                                                function (callbackInner) {
                                                    async.waterfall([
                                                        function(callbackInnerInner) {
                                                            ModeratorManagerOperationNote.count({
                                                                "user": userId,
                                                                "operationType" : "置顶",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempTopDateCount) {
                                                                callbackInnerInner(null, tempTopDateCount);
                                                            });
                                                        },
                                                        function(tempTopDateCount, callbackInnerInner) {

                                                            logger.debug('置顶start...' + eachSeriesInnerCount);
                                                            ModeratorManagerOperationNote.find({
                                                                "user": userId,
                                                                "operationType": "取消置顶",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempData) {
                                                                if (tempData == null || tempData.length == 0) {
                                                                    callbackInner(null, tempTopDateCount);
                                                                } else {
                                                                    async.eachSeries(tempData, function (tempRow, callbackTempInner2) {
                                                                        var tempDateCreated = tempRow.dateCreated;
                                                                        var questionId = tempRow.question;
                                                                        var tempBefore6hDate = moment(tempDateCreated).add(-6, "hour").format();
                                                                        ModeratorManagerOperationNote.count({
                                                                            "user": userId,
                                                                            "question": questionId,
                                                                            "operationType": "置顶",
                                                                            'dateCreated': {
                                                                                $gte: tempBefore6hDate,
                                                                                $lte: tempDateCreated
                                                                            }
                                                                        }, function (tempErr, tempTopIn6hCount) {
                                                                            if (tempTopIn6hCount > 0) {
                                                                                tempTopDateCount = tempTopDateCount - 1;
                                                                            }
                                                                            callbackTempInner2(false);
                                                                        });
                                                                    }, function (tempError) {
                                                                        callbackInner(null, tempTopDateCount);
                                                                    })
                                                                }
                                                            });
                                                        }
                                                    ], function(err, tempData) {
                                                        logger.debug('置顶end...' + eachSeriesInnerCount);
                                                        callbackInner(null, tempData);
                                                    });
                                                },

                                                // 精华
                                                function (callbackInner) {
                                                    logger.debug('精华start...' + eachSeriesInnerCount);
                                                    async.waterfall([
                                                        function(callbackInnerInner) {
                                                            ModeratorManagerOperationNote.count({
                                                                "user": userId,
                                                                "operationType" : "精华",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempEssenceCount) {
                                                                callbackInnerInner(null, tempEssenceCount);
                                                            });
                                                        },
                                                        function(tempEssenceCount, callbackInnerInner) {

                                                            ModeratorManagerOperationNote.count({
                                                                "user": userId,
                                                                "operationType" : "取消精华",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempCount) {
                                                                callbackInnerInner(null, tempEssenceCount - tempCount);
                                                            });
                                                        }
                                                    ], function(err, tempData) {
                                                        logger.debug('精华end...' + eachSeriesInnerCount);
                                                        callbackInner(null, tempData);
                                                    });
                                                },
                                                // 屏蔽
                                                function (callbackInner) {
                                                    logger.debug('屏蔽start...' + eachSeriesInnerCount);
                                                    async.waterfall([
                                                        function(callbackInnerInner) {
                                                            ModeratorManagerOperationNote.count({
                                                                "user": userId,
                                                                "operationType" : "屏蔽",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempEssenceCount) {
                                                                callbackInnerInner(null, tempEssenceCount);
                                                            });
                                                        },
                                                        function(tempEssenceCount, callbackInnerInner) {

                                                            ModeratorManagerOperationNote.count({
                                                                "user": userId,
                                                                "operationType" : "取消屏蔽",
                                                                'dateCreated': {$gte: startDate, $lt: endDate}
                                                            }, function (tempErr, tempCount) {
                                                                callbackInnerInner(null, tempEssenceCount - tempCount);
                                                            });
                                                        }
                                                    ], function(err, tempData) {
                                                        logger.debug('屏蔽end...' + eachSeriesInnerCount);
                                                        callbackInner(null, tempData);
                                                    });
                                                },
                                                function (callbackInner) {
                                                    // 小区名称
                                                    logger.debug('小区start...' + eachSeriesInnerCount);
                                                    var community = tempUser.community;
                                                    if(community) {
                                                        Community.findOne({
                                                            "_id": community
                                                        }, {'communityName': 1, '_id': -1}, function (err, communityName) {
                                                            logger.debug('小区end...' + eachSeriesInnerCount);
                                                            callbackInner(null, communityName);
                                                        });
                                                    } else {
                                                        logger.debug('小区end...' + eachSeriesInnerCount);
                                                        callbackInner(null, null);
                                                    }
                                                },
                                                function (callbackInner) {
                                                    // 城市名称
                                                    logger.debug('城市start...' + eachSeriesInnerCount);
                                                    var cityId = tempUser.cityId;
                                                    if(cityId) {
                                                        Region.findOne({
                                                            "_id": cityId
                                                        }, {'name': 1, '_id': -1}, function (err, regionName) {
                                                            logger.debug('城市end...' + eachSeriesInnerCount);
                                                            callbackInner(null, regionName);
                                                        });
                                                    } else {
                                                        logger.debug('城市end...' + eachSeriesInnerCount);
                                                        callbackInner(null, null);
                                                    }
                                                }
                                            // ], function (errInnerInner, result) {
                                            ], parallelLimitCount, function (errInnerInner, result) {
                                                logger.info('async.seriesN个执行完成...' + eachSeriesInnerCount);
                                                // var hrtimeStart = process.hrtime();
                                                // 小区名称
                                                var communityName = "";
                                                if(result[8]) {
                                                    communityName = result[8].communityName;
                                                }
                                                // 城市名称
                                                var cityName = "";
                                                if(result[9]) {
                                                    cityName = result[9].name;
                                                }
                                                // 手机号码
                                                var mobilePhone = tempUser.mobilePhone;
                                                // 昵称
                                                var nickName = tempUser.nickName;
                                                // 选定日期范围内每天是否登录
                                                var loginDaysCount = toolUtil.getNumberSumByArray(result[0]);
                                                // 选定日期范围内成功邀请人数（总数）
                                                var successInviteUserCount = result[1];
                                                // 问问发布数
                                                var questionCount = result[2];
                                                // 说说发布数
                                                var shareCount = result[3];
                                                // 闲置发布数
                                                var goodsCount = result[4];
                                                // 选定日期范围内每天置顶数量
                                                var topDateCount = result[5];

                                                // 选定日期范围内每天设为精华的数据
                                                var essenceDateCount = result[6];

                                                // 选定日期范围内每天屏蔽的数据
                                                var shieldingDateCount = result[7];

                                                var tempLineData = {};
                                                tempLineData.cityName = cityName;
                                                tempLineData.communityName = communityName;
                                                tempLineData.mobilePhone = mobilePhone;
                                                tempLineData.nickName = nickName;
                                                tempLineData.loginDaysCount = loginDaysCount;
                                                tempLineData.successInviteUserCount = successInviteUserCount;
                                                tempLineData.questionCount = questionCount;
                                                tempLineData.shareCount = shareCount;
                                                tempLineData.goodsCount = goodsCount;
                                                tempLineData.topDateCount = topDateCount;
                                                tempLineData.essenceDateCount = essenceDateCount;
                                                tempLineData.shieldingDateCount = shieldingDateCount;
                                                // fs.appendFileSync(fileName, line);
                                                dataArray.push(tempLineData);
                                                callbackEachSeriesInner(false);
                                            });
                                        // });
                                    }, function (err) {
                                        // logger.info('execute count...' + (++exeCount));
                                        // if(exeCount >= endCount) {
                                        //     logger.info('dataArray.length...' + (dataArray.length));
                                        //     var rowNumber = 1;
                                        //     var row = ws.getRow(rowNumber);
                                        //     row.getCell(1).value = '城市';
                                        //     row.getCell(2).value = '小区';
                                        //     row.getCell(3).value = '手机号码';
                                        //     row.getCell(4).value = '昵称';
                                        //     row.getCell(5).value = '登陆天数';
                                        //     row.getCell(6).value = '成功邀请人数';
                                        //     row.getCell(7).value = '问问发布数';
                                        //     row.getCell(8).value = '说说发布数';
                                        //     row.getCell(9).value = '闲置发布数';
                                        //     row.getCell(10).value = '置顶数';
                                        //     row.getCell(11).value = '精华数';
                                        //     row.getCell(12).value = '屏蔽数';
                                        //     row.commit;
                                        //     rowNumber++;
                                        //
                                        //     async.eachSeries(dataArray, function (tempLine, callbackOutInner) {
                                        //         // 导出txt文件
                                        //         // var line = tempLine.cityName + '\t'
                                        //         //     + tempLine.communityName + '\t'
                                        //         //     + tempLine.mobilePhone + '\t'
                                        //         //     + tempLine.nickName + '\t'
                                        //         //     + tempLine.loginDaysCount + '\t'
                                        //         //     + tempLine.successInviteUserCount + '\t'
                                        //         //     + tempLine.questionCount + '\t'
                                        //         //     + tempLine.shareCount + '\t'
                                        //         //     + tempLine.goodsCount + '\t'
                                        //         //     + tempLine.topDateCount + '\t'
                                        //         //     + tempLine.essenceDateCount + '\t'
                                        //         //     + tempLine.shieldingDateCount + '\r\n';
                                        //         // fs.appendFileSync(fileName, line); // TXT
                                        //
                                        //         // 导出excel文件
                                        //         var tempRow = ws.getRow(rowNumber);
                                        //         tempRow.getCell(1).value = tempLine.cityName;
                                        //         tempRow.getCell(2).value = tempLine.communityName;
                                        //         tempRow.getCell(3).value = tempLine.mobilePhone;
                                        //         tempRow.getCell(4).value = tempLine.nickName;
                                        //         tempRow.getCell(5).value = tempLine.loginDaysCount;
                                        //         tempRow.getCell(6).value = tempLine.successInviteUserCount;
                                        //         tempRow.getCell(7).value = tempLine.questionCount;
                                        //         tempRow.getCell(8).value = tempLine.shareCount;
                                        //         tempRow.getCell(9).value = tempLine.goodsCount;
                                        //         tempRow.getCell(10).value = tempLine.topDateCount;
                                        //         tempRow.getCell(11).value = tempLine.essenceDateCount;
                                        //         tempRow.getCell(12).value = tempLine.shieldingDateCount;
                                        //         tempRow.commit;
                                        //         rowNumber++;
                                        //         callbackOutInner(false);
                                        //     }, function (err) {
                                        //         wb.xlsx.writeFile(fileName).then(function() {
                                        //         });
                                        //         // callbackSkipCountInner(false);
                                        //         callbackInnerTempTemp(null, tempUserCount);
                                        //     });
                                        // }
                                            callbackSkipCountInner(false);
                                    });
                                        // logger.info('execute count...' + (++exeCount));
                                        // if(exeCount >= endCount) {
                                        //     var timeOut = 1 * tempUserCount * length;
                                        //     logger.info("设置等待时间(毫秒数): " + timeOut);
                                        //     setTimeout(function () {
                                        //         logger.info("exportModeratorManagerInfoData real end...");
                                        //         // callback(null, tempUserCount);
                                        //         callbackInnerTempTemp(null, tempUserCount);
                                        //     },timeOut);
                                        // }
                                    } else {
                                        callbackSkipCountInner(false);
                                    }
                                });
                        } , function (err5) {
                                // callbackInnerTempTemp(null, tempUserCount);
                            // logger.info('execute count...' + (++exeCount));
                            // if(exeCount >= endCount) {
                                logger.info('dataArray.length...' + (dataArray.length));
                                var rowNumber = 1;
                                var row = ws.getRow(rowNumber);
                                row.getCell(1).value = '城市';
                                row.getCell(2).value = '小区';
                                row.getCell(3).value = '手机号码';
                                row.getCell(4).value = '昵称';
                                row.getCell(5).value = '登陆天数';
                                row.getCell(6).value = '成功邀请人数';
                                row.getCell(7).value = '问问发布数';
                                row.getCell(8).value = '说说发布数';
                                row.getCell(9).value = '闲置发布数';
                                row.getCell(10).value = '置顶数';
                                row.getCell(11).value = '精华数';
                                row.getCell(12).value = '屏蔽数';
                                row.commit;
                                rowNumber++;

                                async.eachSeries(dataArray, function (tempLine, callbackOutInner) {
                                    // 导出txt文件
                                    // var line = tempLine.cityName + '\t'
                                    //     + tempLine.communityName + '\t'
                                    //     + tempLine.mobilePhone + '\t'
                                    //     + tempLine.nickName + '\t'
                                    //     + tempLine.loginDaysCount + '\t'
                                    //     + tempLine.successInviteUserCount + '\t'
                                    //     + tempLine.questionCount + '\t'
                                    //     + tempLine.shareCount + '\t'
                                    //     + tempLine.goodsCount + '\t'
                                    //     + tempLine.topDateCount + '\t'
                                    //     + tempLine.essenceDateCount + '\t'
                                    //     + tempLine.shieldingDateCount + '\r\n';
                                    // fs.appendFileSync(fileName, line); // TXT

                                    // 导出excel文件
                                    var tempRow = ws.getRow(rowNumber);
                                    tempRow.getCell(1).value = tempLine.cityName;
                                    tempRow.getCell(2).value = tempLine.communityName;
                                    tempRow.getCell(3).value = tempLine.mobilePhone;
                                    tempRow.getCell(4).value = tempLine.nickName;
                                    tempRow.getCell(5).value = tempLine.loginDaysCount;
                                    tempRow.getCell(6).value = tempLine.successInviteUserCount;
                                    tempRow.getCell(7).value = tempLine.questionCount;
                                    tempRow.getCell(8).value = tempLine.shareCount;
                                    tempRow.getCell(9).value = tempLine.goodsCount;
                                    tempRow.getCell(10).value = tempLine.topDateCount;
                                    tempRow.getCell(11).value = tempLine.essenceDateCount;
                                    tempRow.getCell(12).value = tempLine.shieldingDateCount;
                                    tempRow.commit;
                                    rowNumber++;
                                    callbackOutInner(false);
                                }, function (err) {
                                    logger.info("start write excel...");
                                    wb.xlsx.writeFile(fileName).then(function() {
                                    });
                                    logger.info("exportModeratorManagerInfoData real end...");
                                    callbackInnerTempTemp(null, tempUserCount);
                                });
                            // }
                        });
                    }
                });
            // callbackInner(null, 'done');
            }
        ], function(err, tempUserCount) {
            callback(null, tempUserCount);
        });
    } catch(e) {
        console.log(e);
        callback('fail', null);
    }
};
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170925  end   */

// exports.exportModeratorManagerInfoData = function (req, res, callback) {
//     console.log("exportModeratorManagerInfoData real start...");
//
//     try{
//         var limitCount = 20; // mongodb每次查询件数
//         var exeCount = 0;
//
//         var option = {"userRole" : 4}; // 小区大使
//         // var option = {}; // 全部用户
//
//         var wb = new Workbook();
//         var ws = wb.addWorksheet('ModeratorManager');
//
//         // 自动覆盖旧版本，只能同时出现一个
//         var excelName = outPutModeratorManagerInfoBasePath;
//         // 头部第一行
//         var row = ws.getRow(1);
//         row.getCell(1).value = '城市';
//         row.getCell(2).value = '小区';
//         row.getCell(3).value = '手机号码';
//         row.getCell(4).value = '昵称';
//         row.getCell(5).value = '登陆天数';
//         row.getCell(6).value = '成功邀请人数';
//         row.getCell(7).value = '问问发布数';
//         row.getCell(8).value = '说说发布数';
//         row.getCell(9).value = '闲置发布数';
//         row.getCell(10).value = '置顶数';
//         row.getCell(11).value = '精华数';
//         row.getCell(12).value = '屏蔽数';
//         row.getCell(13).value = '日期/总计';
//         row.commit;
//         wb.xlsx.writeFile(excelName)
//             .then(function() {
//                 // console.log('Done...');
//             });
//
//         Users.count(option, function (err, tempUserCount) {
//             console.log('小区大使件数:' + tempUserCount);
//             if(tempUserCount > 0) {
//                 var tmpCountCount = 0;
//                 var startDateSelect = req.body.startDateSelect;
//                 var endDateSelect = req.body.endDateSelect;
//
//                 /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 start */
//                 // var dateArr = toolUtil.getArrayDateByStartEndDate(startDateSelect, endDateSelect);
//                 var dateArr = toolUtil.getArrayDateByStartEndDateMin(startDateSelect, endDateSelect);
//                 var length = dateArr.length;
//                 /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 end */
//
//                 var startDate = moment(startDateSelect, "YYYY-MM-DD").format();
//                 var endDate = moment(endDateSelect, "YYYY-MM-DD").add(1, "days").format();
//                 // var testDate = moment(startDate).add(-6, "hour").format();
//
//                 var dateOption = {'dateCreated': {$gte: startDate, $lt: endDate}};
//
//                 var endCount = parseInt((tempUserCount - 1) / limitCount) + 1;
//                 for(var i = 0; i < tempUserCount; i = i + limitCount) {
//                     Users.find(option)
//                         .populate('community', 'communityName')
//                         .populate('cityId', 'name')
//                         .limit(limitCount)
//                         .skip(i)
//                         .sort({"_id": 1})
//                         .exec(function (err2, usersData) {
//                             if (usersData != null) {
//                                 usersData.forEach(function (tempUser, index, array) {
//                                     console.log("usersData.forEach" + tmpCountCount++);
//                                     var userId = tempUser._id.toString();
//                                     // 并行
//                                     async.series([
//                                         // function (callbackInner) {
//                                         //     // 按照年月日聚合后，取得年月日列表件数即可
//                                         //     SystemAppstartinfos.aggregate([
//                                         //         {$match: {"userId": userId}},
//                                         //         {
//                                         //             $group: {
//                                         //                 _id: {$dateToString: {format: "%Y-%m-%d", date: "$dateCreated"}},
//                                         //                 num_tutorial: {$sum: 1}
//                                         //             }
//                                         //         },
//                                         //         {$sort: {dateCreated: -1}}], function (err, appStartDateList) {
//                                         //         // 每天登陆几次包含在appStartDateList中
//                                         //         var tempAppStartDateLength = 0;
//                                         //         async.eachSeries(appStartDateList, function (tempAppStartDate, callbackInnerInner) {
//                                         //             var tempDateCreated = tempAppStartDate._id;
//                                         //             if(tempDateCreated >= startDateSelect) {
//                                         //                 if(tempDateCreated < endDateSelect) {
//                                         //                     tempAppStartDateLength ++;
//                                         //                     callbackInnerInner(false);
//                                         //                 }
//                                         //             } else {
//                                         //                 return callbackInnerInner(false);
//                                         //             }
//                                         //         }, function (err4) {
//                                         //             callbackInner(null, tempAppStartDateLength);
//                                         //         })
//                                         //     });
//                                         // },
//                                         /* 选定日期范围内是否每天登录 change wangc 20170921 start */
//                                         function (callbackInner) {
//                                             // 选定日期范围内是否每天都登录过至少一次
//                                             var tempLoginDatesArr = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 SystemAppstartinfos.count({
//                                                     "userId": userId,
//                                                     "dateCreated": {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempEssenceCount) {
//                                                     tempLoginDatesArr.push(tempEssenceCount > 0 ? 1 : 0);
//                                                     callbackTempInner(false);
//                                                 });
//                                             }, function (tempErr) {
//                                                 callbackInner(null, tempLoginDatesArr);
//                                             });
//                                         },
//                                         /* 选定日期范围内是否每天登录 change wangc 20170921 end */
//                                         function (callbackInner) {
//                                             // [邀请分享]表取得小区大使对应的邀请码,再到[用户]表中取得邀请码一致的人的件数
//                                             // TODO
//                                             // UserInvitationShare.findOne({"inviter": userId}, 'invitationCode: 1, _id: 0', function (err, invitationInfo) {
//                                             //     if (invitationInfo != null) {
//                                             //         // TODO
//                                             //         // 追加开始结束日期
//                                             //         // 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             //         Users.count({"invitationCode": invitationInfo._doc.invitationCode}, function (err, successInviteUserCount) {
//                                             //             callbackInner(null, successInviteUserCount);
//                                             //         });
//                                             //     } else {
//                                             //         callbackInner(null, 0);
//                                             //     }
//                                             // });
//                                             // 邀请
//                                             // 选定日期范围内邀请成功总数
//                                             UserInvitation.count({
//                                                 "inviter": userId,
//                                                 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             }, function (err, successInviteUserCount) {
//                                                 callbackInner(null, successInviteUserCount);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 问问:question
//                                             // 追加开始结束日期
//                                             // 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             Question.count({
//                                                 "createdBy": userId,
//                                                 "category": "question",
//                                                 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             }, function (err, questionCount) {
//                                                 callbackInner(null, questionCount);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 说说:share
//                                             // 追加开始结束日期
//                                             // 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             Question.count({
//                                                 "createdBy": userId,
//                                                 "category": "share",
//                                                 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             }, function (err, shareCount) {
//                                                 callbackInner(null, shareCount);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 闲置
//                                             // 追加开始结束日期
//                                             // 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             Goods.count({
//                                                 "createdBy": userId,
//                                                 'dateCreated': {$gte: startDate, $lt: endDate}
//                                             }, function (err, goodsCount) {
//                                                 callbackInner(null, goodsCount);
//                                             });
//                                         },
//                                         // function (callbackInner) {
//                                         //     // 小区大使:置顶,精华,屏蔽的数据
//                                         //     ModeratorManager.findOne({"user": userId}, function (err, moderatorManagerData) {
//                                         //         callbackInner(null, moderatorManagerData);
//                                         //     });
//                                         // },
//                                         /* 追加选定日期范围内每天置顶的数据 add wangc 20170921 start */
//                                         function (callbackInner) {
//                                             var moderatorManagerData = {};
//                                             var tempArray = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 ModeratorManagerOperationNote.count({
//                                                     "user": userId,
//                                                     "operationType" : "置顶",
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempTopDateCount) {
//                                                     ModeratorManagerOperationNote.find({
//                                                         "user": userId,
//                                                         "operationType" : "取消置顶",
//                                                         'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                     }, function (tempErr, tempData) {
//                                                         if(tempData == null || tempData.length == 0) {
//                                                             tempArray.push(tempTopDateCount);
//                                                             callbackTempInner(false);
//                                                         } else {
//                                                             async.eachSeries(tempData, function (tempRow, callbackTempInner2) {
//                                                                 var tempDateCreated = tempRow.dateCreated;
//                                                                 var questionId = tempRow.question;
//                                                                 var tempBefore6hDate = moment(tempDateCreated).add(-6, "hour").format();
//                                                                 ModeratorManagerOperationNote.count({
//                                                                     "user": userId,
//                                                                     "question": questionId,
//                                                                     "operationType" : "置顶",
//                                                                     'dateCreated': {$gte: tempBefore6hDate, $lte: tempDateCreated}
//                                                                 },function(tempErr, tempTopIn6hCount) {
//                                                                     if (tempTopIn6hCount > 0) {
//                                                                         tempTopDateCount = tempTopDateCount - 1;
//                                                                     }
//                                                                     callbackTempInner2(false);
//                                                                 });
//                                                             }, function (tempError) {
//                                                                 tempArray.push(tempTopDateCount);
//                                                                 callbackTempInner(false);
//                                                             })
//                                                         }
//                                                     });
//                                                 });
//                                             }, function (tempError) {
//                                                 callbackInner(null, tempArray);
//                                             })
//                                         },
//                                         /* 追加选定日期范围内每天置顶的数据 add wangc 20170921 end */
//
//                                         /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 start */
//                                         function (callbackInner) {
//                                             // 问问：question
//                                             // 查询选定的日期围内的每天发布的问问数量
//                                             var tempQuestionArr = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 Question.count({
//                                                     "createdBy": userId,
//                                                     "category": "question",
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempQuestionCount) {
//                                                     tempQuestionArr.push(tempQuestionCount);
//                                                     callbackTempInner(false);
//                                                 });
//                                             },function (tempErr) {
//                                                 callbackInner(null, tempQuestionArr);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 说说：share
//                                             // 查询选定的日期范围内的每天的说说数据
//                                             var tempShareArr = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 Question.count({
//                                                     "createdBy": userId,
//                                                     "category": "share",
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempShareCount) {
//                                                     tempShareArr.push(tempShareCount);
//                                                     callbackTempInner(false);
//                                                 });
//                                             },function (tempErr) {
//                                                 callbackInner(null, tempShareArr);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 闲置：goods
//                                             // 查询选定的日期范围内的每天的闲置数据
//                                             var tempGoodsArr = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 Goods.count({
//                                                     "createdBy": userId,
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempGoodsCount) {
//                                                     tempGoodsArr.push(tempGoodsCount);
//                                                     callbackTempInner(false);
//                                                 });
//                                             },function (tempErr) {
//                                                 callbackInner(null, tempGoodsArr);
//                                             });
//                                         },
//                                         /* 导出小区大使信息,添加按日期导出每天的数据 add wangc 20170919 end */
//
//                                         /* 追加选定日期范围内的登录,邀请成功人数,置顶,精华,屏蔽数据 add wangc 20170921 start */
//                                         // function (callbackInner) {
//                                         //     // 登录总天数（选定日期范围内）
//                                         //
//                                         // },
//                                         function (callbackInner) {
//                                             // 邀请成功人数（选定日期范围内每天的数据）
//                                             var tempSuccessInvUserCountArr = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 UserInvitation.count({
//                                                     "inviter": userId,
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, successInviteUserCount) {
//                                                     tempSuccessInvUserCountArr.push(successInviteUserCount);
//                                                     callbackTempInner(false);
//                                                 });
//                                             }, function (tempErr) {
//                                                 callbackInner(null, tempSuccessInvUserCountArr);
//                                             });
//                                         },
//                                         function (callbackInner) {
//                                             // 小区大使：精华数据计数（选定日期范围内每天的数据）
//                                             // var moderatorManagerData = {};
//                                             var tempArray = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 ModeratorManagerOperationNote.count({
//                                                     "user": userId,
//                                                     "operationType" : "精华",
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempEssenceCount) {
//                                                     ModeratorManagerOperationNote.count({
//                                                         "user": userId,
//                                                         "operationType" : "取消精华",
//                                                         'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                     }, function (tempErr, tempCount) {
//                                                         tempArray.push(tempEssenceCount - tempCount);
//                                                         callbackTempInner(false);
//                                                     });
//                                                 });
//                                             }, function (tempError) {
//                                                 callbackInner(null, tempArray);
//                                             })
//                                         },
//                                         function (callbackInner) {
//                                             // 小区大使：屏蔽数据计数（选定日期范围内每天的数据）
//                                             // var moderatorManagerData = {};
//                                             var tempArray = [];
//                                             async.eachSeries(dateArr, function (tempDate, callbackTempInner) {
//                                                 var startTemp = tempDate;
//                                                 var endTemp = moment(startTemp, "YYYY-MM-DD").add(1, "days").format();
//                                                 ModeratorManagerOperationNote.count({
//                                                     "user": userId,
//                                                     "operationType" : "屏蔽",
//                                                     'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                 }, function (tempErr, tempEssenceCount) {
//                                                     ModeratorManagerOperationNote.count({
//                                                         "user": userId,
//                                                         "operationType" : "取消屏蔽",
//                                                         'dateCreated': {$gte: startTemp, $lt: endTemp}
//                                                     }, function (tempErr, tempCount) {
//                                                         tempArray.push(tempEssenceCount - tempCount);
//                                                         callbackTempInner(false);
//                                                     });
//                                                 });
//                                             }, function (tempError) {
//                                                 callbackInner(null, tempArray);
//                                             })
//                                         },
//                                         /* 追加选定日期范围内的登录和邀请成功人数数据 add wangc 20170921 end */
//                                     ], function (errInnerInner, result) {
//                                         // var hrtimeStart = process.hrtime();
//                                         // 城市名称
//                                         var cityName = '';
//                                         if(tempUser.cityId) {
//                                             cityName = tempUser.cityId.name;
//                                         }
//                                         // 小区名称
//                                         var communityName = '';
//                                         if(tempUser.community) {
//                                             communityName = tempUser.community.communityName;
//                                         }
//                                         // 手机号码
//                                         var mobilePhone = tempUser.mobilePhone;
//                                         // 昵称
//                                         var nickName = tempUser.nickName;
//                                         // 选定日期范围内每天是否登录
//                                         var appStartDateCount = result[0];
//                                         // 选定日期范围内成功邀请人数（总数）
//                                         var successInviteUserCount = result[1];
//                                         // 问问发布数
//                                         var questionCount = result[2];
//                                         // 说说发布数
//                                         var shareCount = result[3];
//                                         // 闲置发布数
//                                         var goodsCount = result[4];
//                                         // 置顶数
//                                         var topCount = 0;
//                                         // 精华数
//                                         var essenceCount = 0;
//                                         // 屏蔽数
//                                         var shieldingCount = 0;
//                                         // 小区大使信息(置顶,精华,屏蔽)
//                                         // var tempModeratorManager = result[5];
//                                         // if(tempModeratorManager != null) {
//                                         //     topCount = tempModeratorManager._doc.topCount;
//                                         //     essenceCount = tempModeratorManager._doc.essenceCount;
//                                         //     shieldingCount = tempModeratorManager._doc.shieldingCount;
//                                         // }
//                                         // 选定日期范围内每天置顶数量
//                                         var topDateCount = result[5];
//                                         for (var k = 0, arrLength = topDateCount.length; k < arrLength; k++) {
//                                             topCount += topDateCount[k];
//                                         }
//                                         // 小区大使在选定的日期范围内每天的相关数据
//                                         var questionDateCount = result[6];
//                                         var shareDateCount = result[7];
//                                         var goodsDateCount = result[8];
//
//                                         // 选定日期范围内登录的总天数
//                                         var loginDaysCount = 0;
//                                         if (appStartDateCount != null && appStartDateCount.length > 0) {
//                                             for (var k = 0, arrLength = appStartDateCount.length; k < arrLength; k++) {
//                                                 loginDaysCount += appStartDateCount[k];
//                                             }
//                                         }
//
//                                         // 选定日期范围内每天成功邀请的人数
//                                         var successInvUserCount = result[9];
//
//                                         // 选定日期范围内每天设为精华的数据
//                                         var essenceDateCount = result[10];
//                                         for (var k = 0, arrLength = essenceDateCount.length; k < arrLength; k++) {
//                                             essenceCount += essenceDateCount[k];
//                                         }
//                                         // 选定日期范围内每天屏蔽的数据
//                                         var shieldingDateCount = result[11];
//                                         for (var k = 0, arrLength = shieldingDateCount.length; k < arrLength; k++) {
//                                             shieldingCount += shieldingDateCount[k];
//                                         }
//
//                                         for (var j = 0; j <= length; j++) {
//                                             var row = ws.getRow(ws.rowCount + 1);
//                                             row.getCell(1).value = cityName;
//                                             row.getCell(2).value = communityName;
//                                             row.getCell(3).value = mobilePhone;
//                                             row.getCell(4).value = nickName;
//                                             if (j == length) {
//                                                 row.getCell(5).value = loginDaysCount;
//                                                 row.getCell(6).value = successInviteUserCount;
//                                                 row.getCell(7).value = questionCount;
//                                                 row.getCell(8).value = shareCount;
//                                                 row.getCell(9).value = goodsCount;
//                                                 row.getCell(10).value = topCount;
//                                                 row.getCell(11).value = essenceCount;
//                                                 row.getCell(12).value = shieldingCount;
//                                                 row.getCell(13).value = "总计";
//                                             } else {
//                                                 row.getCell(5).value = appStartDateCount[j];
//                                                 row.getCell(6).value = successInvUserCount[j];
//                                                 row.getCell(7).value = questionDateCount[j];
//                                                 row.getCell(8).value = shareDateCount[j];
//                                                 row.getCell(9).value = goodsDateCount[j];
//                                                 row.getCell(10).value = topDateCount[j];
//                                                 row.getCell(11).value = essenceDateCount[j];
//                                                 row.getCell(12).value = shieldingDateCount[j];
//                                                 row.getCell(13).value = moment(dateArr[j], "YYYY-MM-DD").format("YYYY-MM-DD");
//                                             }
//                                             row.commit;
//                                         }
//                                         wb.xlsx.writeFile(excelName).then(function() {
//                                             // console.log('Done...');
//                                             // var hrtimeEnd = process.hrtime(hrtimeStart);
//                                             // console.log("hrtimeEnd:"+hrtimeEnd);
//                                         });
//                                     });
//                                 });
//                                 console.log('execute count...' + (++exeCount));
//                                 if(exeCount >= endCount) {
//                                     // var timeOut = 100 * tempUserCount * length;
//                                     // setTimeout(function () {
//                                         console.log("exportModeratorManagerInfoData real end...");
//                                         callback(null, tempUserCount);
//                                     // },timeOut);
//                                 }
//                             }
//                         });
//                 }
//             }
//         });
//     } catch(e) {
//         console.log(e);
//         callback('fail', null);
//     }
// }
/*  宝宝树66小区二次改造    mod   guo.xiaomin  20170825  end   */
/*  宝宝树66小区二次改造    mod   wangcan 20170922  end   */

exports.getAllCommunityGroupsService = function (callback) {

    var sql = 'select * from 66xiaoqu_rec.community_group'
    mysqlUtil.queryBI(sql, function (err, result) {
        callback(err, result)
    })

    //communityGroup.find({}).exec(function (err, results) {
    //    if (results != null) {
    //        callback(null, results);
    //    } else {
    //        var msg = {
    //            "message": 'No community groups'
    //        }
    //        callback(msg, null);
    //    }
    //});
};


exports.postCommunitySupplementService = function (token, input, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            var temp = new communitySupplement();
            temp.createdBy = user._id;
            temp.desc = input.desc;
            temp.community = user.community._id;
            temp.save(callback);

            var message = '感谢您的理解和支持，如有其它问题，欢迎随时撩我哦~如果你对我印象还不错，欢迎推荐给身边的亲朋好友哈~';
            toolUtil.pushCustomerServiceMessage(user, message);
        }
    });
};

exports.getCommunitySupplementListService = function (communityId, callback) {
    if (communityId == '1') {
        communitySupplement.find({}, 'dateCreated createdBy desc community status').populate('createdBy', 'nickName').populate('community', 'communityName')
            .sort({status: 1, dateCreated: -1}).exec(callback);
    } else {
        communitySupplement.find({community: communityId}, 'dateCreated createdBy desc community status').populate('createdBy', 'nickName').populate('community', 'communityName')
            .sort({status: 1, dateCreated: -1}).exec(callback);
    }
};

exports.updateCommunityService = function (communityId, input, callback) {
    Community.update({_id: communityId}, input, {status: true}, callback)
};

exports.updateSupplementStatusService = function (supplementId, callback) {

    Supplement.update({_id: supplementId}, {status: true}, callback)
};


exports.getAllCommunityNoticeService = function (communityId, callback) {

    var opt = {};
    if (communityId != '1') {
        opt.community = communityId;
    }
    Bulletins.find(opt).populate('community', '_id communityName').sort('-dateCreated').exec(function (err, result) {
        if (result != null) {
            result.forEach(function (topic) {
                topic._doc['url'] = NoticeHost + '/' + topic._id + '.html'
            });
        }
        callback(err, result);
    });
};

exports.setNoticeStatusService = function (input, callback) {
    Bulletins.update({_id: input.id}, {isValid: input.status}, callback);
}

exports.addNoticeToFreshService = function (communityId, noticeId, callback) {
    async.series([
        function (callbackInner) {
            Bulletins.findOne({_id: noticeId}, 'title community', function (err, result) {
                var temp = new freshNews();
                temp.openType = 1;
                temp.tag = freshName.notice.tagName;
                temp.bgColor = freshName.notice.bgColor;
                temp.newsId = result._id;
                temp.title = result.title;
                temp.community = result.community;
                temp.save(callbackInner);
            });
        }
        //function (callbackInner) {
        //    Bulletins.find({community: communityId}, function (err, results) {
        //        async.each(results, function (temp, callback1) {
        //            temp.isFresh = false;
        //            temp.save(callback1);
        //        }, function (err) {
        //            callbackInner(err, null);
        //        })
        //    });
        //},
        //function (callbackInner) {
        //    Bulletins.update({_id: noticeId}, {isFresh: true}, callbackInner);
        //}
    ], callback)
};

exports.getCommunityPeopleNumberService = function (token, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null);
        } else {
            Users.count({community: user.community._id}, callback);
        }
    })
};

exports.getCommunityUserService = function (token, ts, callback) {
    toolUtil.getUserByToken(token, function (err, user) {
        if (err) {
            callback(err, null)
        } else {
            var opt = {
                community: user.community._id,
                nickName: {$ne: null},
                authenticationStatus: true
            };
            if (ts != '0') {
                opt.pinyinSort = {$gt: ts}
            }

            Users.find(opt, 'nickName images roomUnit userPortrait gender userType authenticationStatus pinyinSort')
                .populate('userPortrait', 'value').limit(listPageSize).sort('pinyinSort').exec(function (err, results) {
                    if (results != null) {
                        results.forEach(function (user) {
                            if (user.userPortrait == null) {
                                user.userPortrait = undefined;
                            }
                        })
                    }
                    if (ts == '0') {
                        Users.findOne({
                            userType: 'service',
                            community: user.community._id
                        }, 'nickName images roomUnit userPortrait gender userType authenticationStatus pinyinSort')
                            .populate('userPortrait', 'value').exec(function (err, user) {
                                if (user != null)
                                    results.unshift(user);
                                callback(err, results)
                            })
                    } else {
                        callback(err, results);
                    }
                })
        }
    })
};

exports.deleteNoticeService = function (noticeId, callback) {
    Bulletins.remove({_id: noticeId}).exec(callback);
};

exports.deleteNoticeServiceByModerator = function (noticeId, communityId, callback) {
    Bulletins.update({_id: noticeId}, {$pull: {community: communityId}}, function () {
        freshNews.update({newsId: noticeId}, {$pull: {community: communityId}}, function () {
            Banner.findOne({contentId: noticeId}, function (err, result) {
                if (result != null) {
                    BannerBind.remove({bannerId: result._id, community: communityId}).exec(callback);
                }
            });
        });
    });
};

exports.getNoticeByIdService = function (noticeId, callback) {
    Bulletins.findOne({_id: noticeId}, callback)
};

exports.initCommunityAround = function (callback) {
    Community.find({isValid: true}, function (err, result) {

            for (var i = 0; i < result.length; i++) {
                var key = "around:community:" + result[i]._id.toString();
                redisClient.DEL(key);
            }

            for (var i = 0; i < result.length; i++) {
                var communitys = "";
                for (var j = 0; j < result.length; j++) {
                    if (result[i].location != null && result[j].location != null) {
                        var distance = geolib.getDistance(
                            {latitude: result[i].location.latitude, longitude: result[i].location.longitude},
                            {latitude: result[j].location.latitude, longitude: result[j].location.longitude}
                        );
                        if (aroundCommunityMeter >= distance && result[i]._id != result[j]._id) {
                            communitys += result[j].communityName + ",";
                            var key = "around:community:" + result[i]._id.toString();
                            //redisClient.DEL(key);
                            //logger.info(key);
                            //logger.info(result[j]._id.toString());
                            redisClient.ZADD(key, distance, result[j]._id.toString());
                        }
                    }
                }
                logger.info(result[i].communityName + "的关联小区>>>>" + communitys);
            }
            callback();
        }
    )
};

exports.getCommunityGroups = function (input, callback) {

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 20;
    var offset = (currentPage - 1) * pageSize;

    async.series([

        function (callbackInner) {
            communityGroup.find({}).skip(offset).sort('-dateCreated').limit(pageSize)
                .exec(function (err, result) {//limit(pageSize)
                async.each(result, function (group, callbackInner) {
                    var communities = "";
                    Community.find({groups: group._id}, function (err, cies) {
                        for (var i = 0; i < cies.length; i++) {
                            communities += cies[i].communityName + ",";
                        }
                        group._doc.communities = communities;
                        callbackInner();
                    });

                }, function (err) {
                    callbackInner(err, result);
                });
            });
        },
        function (callbackInner) {
            communityGroup.count({}, function (err, result) {
                var totalPage = 0;
                if (result != null) {
                    var count = result;
                    var totalPage = Math.ceil(count / pageSize);
                }
                callbackInner(err, totalPage);
            });
        }
    ], callback);

};

exports.addCommunityGroup = function (input, callback) {

    var cyGroup = new communityGroup();

    cyGroup.groupName = input.groupName;

    cyGroup.save();

    callback();

};

exports.updateCommunityGroup = function (input, callback) {

    var groupId = input.groupId;
    var groupName = input.groupName;

    communityGroup.update({_id: groupId}, {groupName: groupName}, function (err) {
        callback();
    });

};

exports.deleteCommunityGroup = function (input, callback) {

    var groupId = input.groupId;

    communityGroup.remove({_id: groupId}, function () {
        Community.update({groups:groupId},{$pull: {groups: groupId}},function(){
            callback();
        });
    });

};

exports.getCommunityGroupById = function (input, callback) {

    var groupId = input.groupId;

    communityGroup.findOne({_id: groupId}, function (err, result) {
        callback(err, result);
    });

};

exports.getCommunitiesByGroup = function (input, callback) {

    var groupId = input.groupId;

    var currentPage = 1;
    if (input.currentPage != '' && input.currentPage != null) {
        currentPage = input.currentPage;
    }
    var pageSize = 10;
    var offset = (currentPage - 1) * pageSize;

    var condition = {
        groups: groupId
    }

    async.series([

        function (callbackInner) {
            Community.find(condition).skip(offset).limit(pageSize).exec(function (err, result) {
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            Community.count(condition, function (err, result) {
                var totalPage = 0;
                if (result != null) {
                    var count = result;
                    totalPage = Math.ceil(count / pageSize);
                }
                callbackInner(err, totalPage);
            });
        }
    ], callback);

};

exports.deleteCommunityGroups = function (input, callback) {

    var groupId = input.groupId;
    var communityId = input.communityId;

    Community.update({_id: communityId}, {$pull: {groups: groupId}}, function () {
        callback();
    });

};

exports.getIsOpenCommunityByName = function (input, callback) {
    logger.info(input.communityName);

    var communityName = input.communityName;
    Community.find({
        $or: [{
            communityName: new RegExp(communityName),
            isValid: true,
            groups: null
        }, {communityName: new RegExp(communityName), isValid: true, groups: []}]
    }, function (err, result) {
        callback(err, result);
    });

};

exports.insertCommunityGroups = function (input, callback) {

    var groupId = input.groupId;
    var communityIds = input.communityIds;

    logger.info(communityIds.split(',').length);


    for (var i = 0; i < communityIds.split(',').length; i++) {
        logger.info(communityIds.split(',')[i]);
        Community.update({_id: communityIds.split(',')[i]}, {$addToSet: {groups: groupId}}, function () {
            Community.findOne({_id: communityIds.split(',')[i]}, function (err, result) {
                logger.info(result);
            });
        });

    }
    callback();

};